<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose 
 */

use \GatewayWorker\Lib\Gateway;

use App\Chat\User;



class Events
{

    public static function onWorkerStart($businessWorker)
    {
        User::MysqlInit();
    }
   /**
    * 有消息时
    * @param int $client_id
    * @param mixed $message
    */
   public static function onMessage($client_id, $message)
   {

        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:"
              .json_encode($_SESSION)
              ." onMessage:"
              . $message."\n";


       // 客户端传递的是json数据
       $message_data = json_decode($message, true);

       $lang = isset($message_data["lang"]) ? $message_data["lang"] :"en";

       echo $lang;

        if(!$message_data)
        {
            echo "no msg data";
            return ;
        }
        //心跳返回
        if($message_data['type']=="pong"){
            return;
        }


        //获取全局可能用到信息
       $role = $message_data['role'];
       $room_id = $message_data['room_id'];
       $siteId =  isset($message_data['site_id']) ? $message_data['site_id'] : 0;
       $client_name = isset($message_data['client_name']) ? $message_data['client_name'] : "no client name" ;
       $to_client_id =isset($message_data['to_client_id']) ? $message_data['to_client_id'] : null ;
       switch($message_data['type'])
        {
            // 客户端登录 message格式: {type:login, name:xx, room_id:1} ，添加到客户端，广播给所有客户端xx进入聊天室
            case 'login':
                echo "login \n";
//                 判断是否有唯一标识
                if(!isset($message_data['room_id']))
                {
                    throw new Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
                }
		User::setConnectNum();
	        $conNum = User::getConnectNum(); echo $conNum."\n";	
                $login =  User::login($client_id,$message_data);
                if($login==false){
                    Gateway::sendToCurrentClient(json_encode("login fail"));
                    return ;
                }
                $adminList = User::getUserList(User::ADMIN,$room_id);
                $visitorList = User::getUserList(User::VISITOR,$room_id);
                $adminClentIdList = $adminList ?   array_keys($adminList) : [];
                $visitorClentIdList = $visitorList ?  array_keys($visitorList) : [];
                $visitor_message = array('role'=>$role,'type'=>$message_data['type'], 'client_id'=>$client_id, 'client_name'=>htmlspecialchars($client_name), 'time'=>date('Y-m-d H:i:s'));
                $admin_message = $visitor_message;

                switch ($role){
                    case User::ADMIN:
                        //添加上访客的id列表；
                        $admin_message['client_info'] = $visitorList;
                        //给访客发送后台客服人员信息；
                        Gateway::sendToCurrentClient(json_encode($admin_message,JSON_UNESCAPED_UNICODE));
                        //上线通知其他客服;
                        Gateway::sendToAll(json_encode($admin_message,JSON_UNESCAPED_UNICODE),$adminClentIdList,[$client_id]);
                        break;
                    case User::VISITOR:
                        //给访客发送后台客服人员信息；
                        $admin_message['client_info'] = $adminList;
                        Gateway::sendToCurrentClient(json_encode($admin_message,JSON_UNESCAPED_UNICODE));
                        //给后台客服发送上线通知;
                        $visitor_message['client_info'] = $visitorList;
//                        echo "\n";
//                        var_dump( $visitorList);
//                        echo "\n";
                        Gateway::sendToAll(json_encode($visitor_message,JSON_UNESCAPED_UNICODE),$adminClentIdList);

                        break;
                }

                return;
                
            // 客户端发言 message: {type:say, to_client_id:xx, content:xx}
            case 'say':
                echo "say \n";
                // 非法请求
                if(!isset($_SESSION['room_id'])) {
                    throw new Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}");
                }
                $adminList = User::getUserList(User::ADMIN,$room_id);
                $visitorList = User::getUserList(User::VISITOR,$room_id);
                $adminClentIdList = $adminList ?   array_keys($adminList) : [];
                $visitorClentIdList = $visitorList ?  array_keys($visitorList) : [];

                switch ($role){
                    case User::ADMIN:
                        echo "say admin \n";
                        if(empty($to_client_id)){
                            throw new Exception("admin send to visitor fail miss to client_id");
                        }
                        $new_message = array(
                            'type'=>'say',
                            'from_client_id'=>$client_id,
                            'client_name' =>$client_name,
                            'to_client_id'=>$to_client_id,
                            'content'=>nl2br(htmlspecialchars($message_data['content'])),
                            'time'=>date('Y-m-d H:i:s'),
                            'role'=>User::ADMIN,
                            'avatar'=>$message_data['avatar']
                        );

                        Gateway::sendToClient($to_client_id,json_encode($new_message));
                        Gateway::sendToAll(json_encode($new_message),$adminClentIdList,$client_id);
                        break;
                    case User::VISITOR:
                        echo "say visitor \n";
                        $new_message = array(
                            'type'=>'say',
                            'from_client_id'=>$client_id,
                            'client_name' =>$client_name,
                            'to_client_id'=>$message_data['to_client_id'],
                            'content'=>nl2br(htmlspecialchars($message_data['content'])),
                            'time'=>date('Y-m-d H:i:s'),
                            'content'=>nl2br(htmlspecialchars($message_data['content'])),
                            'role'=>User::VISITOR,
                            'avatar'=>$message_data['avatar']

                        );
                        //匹配到特殊规定的字符就自动回复客户端
                        $isAutoReplay = false;
                        $content = $new_message["content"];
                        User::DoMsgFilter($content,$isAutoReplay,$siteId);
                        if ($isAutoReplay){
                            $new_message["content"] =$content;
                            $new_message["visitor"] ="admin";
                            Gateway::sendToClient($client_id,json_encode($new_message));
                            return;
                        }

                        Gateway::sendToAll(json_encode($new_message),$adminClentIdList);
                        break;
                    default:
                        echo "no match role \n";
                }
                return;

           default:
               echo "\n no match type  \n";
        }


   }
   
   /**
    * 当客户端断开连接时
    * @param integer $client_id 客户端id
    */
   public static function onClose($client_id)
   {
       // debug
       echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";
       
       // 从房间的客户端列表中删除
       if(isset($_SESSION['room_id']))
       {
           $room_id = $_SESSION['room_id'];
           User::setConnectNum(-1);
           User::updateGroupClientInfo($room_id);
           $new_message = array('type'=>'logout', "role"=>$_SESSION["role"],'from_client_id'=>$client_id,'client_name'=>$_SESSION['client_name'], 'from_client_name'=>$_SESSION['client_name'], 'time'=>date('Y-m-d H:i:s'));
           $adminList = User::getUserList(User::ADMIN,$room_id);
           $visitorList = User::getUserList(User::VISITOR,$room_id);
           $adminClentIdList = $adminList ?   array_keys($adminList) : [];
           $visitorClentIdList = $visitorList ?  array_keys($visitorList) : [];
           Gateway::sendToAll(json_encode($new_message),$adminClentIdList);
           //如果客服的数量为0，就要通知前端访客客服已下线
           if(count($visitorClentIdList)){
               Gateway::sendToAll(json_encode($new_message),$visitorClentIdList);
           }
       }
   }
  
}
